<template>
    <div class="dynamic-data-analysis" v-loading="loading" loading-text="加载数据中...">
        <BaseChart ref="chart" :options="chartOption"></BaseChart>
    </div>
</template>

<script setup>
import { getMeterDetailApi } from '@/api/meter';
import BaseChart from '@/components/chart/BaseChart.vue';
import { watchEffect, ref, computed } from 'vue'
import dayjs from 'dayjs'
let loading = ref(false)
let chart = ref(null)

let props = defineProps({
    id: {
        type: [String, Number],
        default: null
    },
    dateRange: {
        type: Array,
        default: () => []
    },
})

let meterData = ref([])
const chartOption = computed(() => {
    return {
        title: "",
        xAxisData: meterData.value.map(item => item.time),
        yAxisUnit: "m³",
        series: [{
            name: "流量",
            type: 'line',
            data: meterData.value.map(item => item.value),
            showExtremum: true
        }],
        showMarkLine: true,
        iszoom: true,
        isMerge: false,
    }
})
const fetchMeterData = async (id, startDate, endDate) => {
    loading.value = true
    try {
        let res = await getMeterDetailApi({
            id: id,
            start_time: startDate,
            end_time: endDate,
        })

        if (res.code !== 200) {
            ElMessage.error(res.message || '动态数据分析失败')

            return
        }

        meterData.value = res.meter_readings
            .map((item, index) => {
                const prevValue = index === 0 ? item.value : res.meter_readings[index - 1].value
                return {
                    value: calculateUsage(prevValue, item.value).toFixed(2),
                    time: dayjs(item.time).format('MM-DD HH:mm')
                }
            }).slice(1)

    } catch (error) {

        ElMessage.error('服务器异常，动态数据分析失败')
    } finally {
        loading.value = false
    }
}

// 假设这是您的计算用量函数
const calculateUsage = (prevValue, currentValue) => {
    // 如果是第一个值，返回0或其他默认值
    if (prevValue === undefined || prevValue === null) {
        return 0
    }
    // 计算使用量
    return currentValue - prevValue
}

watchEffect(() => {
    if (props.dateRange.length === 2 && props.id) {
        fetchMeterData(props.id, props.dateRange[0], props.dateRange[1])
    }
})
</script>

<style scoped>
.dynamic-data-analysis {
    height: 100%;
    width: 100%;
}
</style>